<template>
  <div class="page">
    <AddressList
      v-model="chooseAddressId"
      :list="list"
      default-tag-text="默认地址"
      @select="selectAddress"
      @add="toPath('/address/edit')"
      @edit="onEdit"
    />
  </div>
</template>
<script lang="ts" setup>
import { selectAddressAll } from "@/api/address";
import { setCookie } from "@/utils/auth";
import enums from "@/utils/enums";
import { AddressList } from "vant";
import { inject, onMounted, ref } from "vue";
import { useRoute } from "vue-router";

const toPath: any = inject("toPath");

/**默认选中的地址 */
const chooseAddressId = ref();
/**地址列表 */
const list = ref([]);
/**是否开启选择栏 */
const choose = ref(true);

const route = useRoute();

onMounted(() => {
  choose.value = Boolean(route.query.choose) || true;
  if (route.query.chooseAddressId) {
    chooseAddressId.value = Number(route.query.chooseAddressId);
    setCookie(enums.cookie.address.chooseAddressId, chooseAddressId.value);
  }

  selectAddressAll().then((res) => {
    list.value = res.data.map((item: any) => {
      return {
        id: item.id,
        name: item.userName + (item.sex == 0 ? "先生" : "女士"),
        tel: item.phoneNumber,
        address: item.address,
        isDefault: item.isDefault,
      };
    });
  });
});
/**编辑地址时跳转到编辑页面 */
const onEdit = (item: any, index: number) => {
  toPath("/address/edit?id=" + item.id);
};
/**选择企业时保存到cookie */
const selectAddress = (item: any, index: number) => {
  setCookie(enums.cookie.address.chooseAddressId, item.id);
};
</script>
